package cn.open.feishu.alert.context;


import cn.open.feishu.alert.common.annotation.AlertHandler;
import cn.open.feishu.alert.support.Handler.FeishuAlertHandler;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.Map;

/**
 * @Description 飞书访问上下文环境
 * @Author fandy.lin
 * @Date 2021/11/22 4:24 下午
 **/
@Data
public class FeishuHandlerContext implements BeanPostProcessor {
    private static volatile Map<String, FeishuAlertHandler> handlerMap;

    public static FeishuAlertHandler getHandler(String handlerName) {
        return handlerMap.get(handlerName);
    }

    public static void addHandler(String name, FeishuAlertHandler handler) {
        if (handlerMap == null) {
            synchronized (FeishuHandlerContext.class) {
                if (handlerMap == null) {
                    handlerMap = Maps.newHashMapWithExpectedSize(8);
                }
            }
        }
        handlerMap.put(name, handler);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (FeishuAlertHandler.class.isAssignableFrom(bean.getClass()) && bean.getClass().isAnnotationPresent(AlertHandler.class)) {
            AlertHandler annotation = bean.getClass().getAnnotation(AlertHandler.class);
            FeishuHandlerContext.addHandler(annotation.value().getType(), (FeishuAlertHandler) bean);
        }
        return bean;
    }
}
